<?php
declare(strict_types=1);

namespace App\Service;

use App\Helper\Log;
use App\Helper\Util;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use App\Service\WxTemplateMessageService;
use App\Service\Pushapp\MpushService;

/**
 * 推送服务
 */
class PushService 
{
    //用户推送设置redis的key
    private $user_push_setting = "grappiao_app:user_push_setting";
    //微信公众号名称
    private $sys_wechat_name = "抢票票助手";
    //如何在公众号中搜索示例图片
    private $sys_wechat_find_example_image = 'app/img/other/find_shoes_wxgzh.png';
    /**
     * [__construct description] 构造函数
     */
    public function __construct()
    {}
    /**
     * 获取用户推送设置信息
     * @return string[]
     */
    public function getSettings($user_id)
    {
        $return_data = [
            'app' => $this->userAppPushSta($user_id),//1开 0关
            'wechat' => $this->userWxPushSta($user_id),//1开 0关
        ];
        return $return_data;
    }
    /**
     * 用户APP推送设置状态
     * [userAppPushSta description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function userAppPushSta($user_id)
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Redis::class);
        $onoff = "1";
        $redis_tag = $user_id.'_app';
        if ($redis->HEXISTS($this->user_push_setting, $redis_tag)) {
            $onoff = $redis->HGET($this->user_push_setting, $redis_tag);
        }
        return $onoff;
    }
    /**
     * 用户微信公众号推送设置状态
     * [userWxPushSta description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function userWxPushSta($user_id)
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Redis::class);
        $onoff = "1";
        $redis_tag = $user_id.'_wechat';
        if ($redis->HEXISTS($this->user_push_setting, $redis_tag)) {
            $onoff = $redis->HGET($this->user_push_setting, $redis_tag);
        }
        return $onoff;
    }
    /**
     * 设置推送设置信息
     * @param $type
     * @param $value
     * @return bool
     */
    public function putSettings($type, $value, $user_id)
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Redis::class);
        $redis_tag = $user_id.'_'.$type;
        $redis->hset($this->user_push_setting, $redis_tag, (string)$value);
        return true;
    }
    /**
     * 统一推送方法
     * [doPush description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function doPush($data)
    {
        $openid = $this->getUserWxOpenid($data['user_id']);
        $reg_info = $this->getUserRegId($data['user_id']);
        $reg_id = $reg_info['reg_id']??NULL;
        $title = "抢票票助手提醒";
        $person_info = $this->getPersonName($data['std_id']);
        $person_name = $person_info['person_name'];
        $show_name = $person_name."演唱会";
        $show_full_name = $person_info['showdate_name'];
        $grab_time = $person_info['grabtime'];
        $showdate_id = $person_info['showdate_id'];

        //微信推送
        $wx_push_sta = $this->userWxPushSta($data['user_id']);
        if(!empty($openid) && $wx_push_sta=="1"){
            $push_param = [
                'openid'=>$openid,
                'title'=>$title,
                'show_name'=>$show_name,
                'grab_time'=>$grab_time,
                'data_id'=>$showdate_id,
                'push_id'=>NULL
            ];
            $user_push_log_data = [
                'user_id'=>$data['user_id'],
                'platform'=>"wechat",
                'device'=>"wechat",
                'sub_id'=>$data['id'],
                'reg_id'=>$openid,
                'content'=>json_encode($push_param, JSON_UNESCAPED_UNICODE),
                'push_time'=>time()
            ];
            $push_id = Db::table('user_push_log')
                ->insertGetId($user_push_log_data);
            $push_param['push_id'] = $push_id;
            $wxtmpServ = new WxTemplateMessageService();
            $res = $wxtmpServ->noticeUserRemind($push_param);
            if($res){
                Db::table('user_sub')
                    ->where(['id'=>$data['id']])
                    ->update(['is_push'=>1]);
            }
        }
        //App推送
        $app_push_sta = $this->userAppPushSta($data['user_id']);
        if(!empty($reg_id) && $app_push_sta=="1"){
            $push_user = [
                'reg_id'=>$reg_info['reg_id']??NULL,
                'app_type'=>$reg_info['device']??NULL,
                'push_type'=>$reg_info['platform']??NULL
            ];
            $push_extra = [
                'data_id'=>$showdate_id,
                'push_id'=>NULL,
                'page'=>'ticket_detail',
                'source'=>'app_push',
                'tag'=>'msg_hit',
                'jump_tag'=>'',
            ];

            $log_param = [
                'push_user'=>$push_user,
                'title'=>$title,
                'content'=>$show_full_name,
                'push_extra'=>$push_extra
            ];
            $user_push_log_data = [
                'user_id'=>$data['user_id'],
                'platform'=>$reg_info['platform'],
                'device'=>$reg_info['device'],
                'sub_id'=>$data['id'],
                'reg_id'=>$reg_id,
                'content'=>json_encode($log_param, JSON_UNESCAPED_UNICODE),
                'push_time'=>time()
            ];
            $push_id = Db::table('user_push_log')
                ->insertGetId($user_push_log_data);
            $push_extra['push_id'] = $push_id;

            $mpServ = new MpushService();
            $res = $mpServ->singlePushByUser($push_user,$title,$show_full_name,$push_extra);
            if($res){
                Db::table('user_sub')
                    ->where(['id'=>$data['id']])
                    ->update(['is_push'=>1]);
            }
        }
    }
    /**
     * 获取人物姓名
     * [getPersonName description]
     * @param  [type] $std_id [description]
     * @return [type]         [description]
     */
    public function getPersonName($std_id)
    {
        $showdate_info = Db::table('vote_showdate_detail')
            ->select(['showdate_id','grabtime'])
            ->where('id', $std_id)
            ->first();
        $showdate_id = $showdate_info['showdate_id'];
        $grabtime = date("Y-m-d H:i", $showdate_info['grabtime']);
        $person_info = Db::table('vote_showdate')
            ->select(['person_id','name'])
            ->where('id', $showdate_id)
            ->first();
        $person_id = $person_info['person_id'];
        $showdate_name = $person_info['name'];
        $person_name = Db::table('vote_person')
            ->where('id', $person_id)
            ->value("name");
        return ['showdate_id'=>$showdate_id,'person_name'=>$person_name,'showdate_name'=>$showdate_name,'grabtime'=>$grabtime];
    }
    /**
     * 获取用户微信公众号openid-推送消息用
     * [getUserWxOpenid description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function getUserWxOpenid($user_id)
    {
        $user_info = Db::table('user')
            ->select(['wx_openid','unionid'])
            ->where('id', $user_id)
            ->first();
        if(empty($user_info['wx_openid'])){
            $user_openid = Db::table('wxship_act')
                ->where('unionid', $user_info['unionid'])
                ->value("openid");
        }else{
            $user_openid = $user_info['wx_openid'];
        }
        return $user_openid;
    }
    /**
     * 获取注册ID
     * [getUserRegId description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function getUserRegId($user_id)
    {
        $user_info = Db::table('user_push_reg')
            ->select(['platform','device','reg_id'])
            ->where('user_id', $user_id)
            ->first();
        return $user_info;
    }
    /**
     * 推送更新为已读
     * [updateRead description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function updateRead($id)
    {
        Db::table('user_push_log')
            ->where(['id'=>$id])
            ->update(['is_hit'=>1]);
        return true;
    }
}
